<?php

namespace App\Http\Controllers\Quiz\Sheet;

use App\Contracts\Repositories\Quiz\SheetRepository as SheetRepositoryContracts;
use App\Contracts\Repositories\QuizRepository as QuizRepositoryContract;
use App\Morefun\Quiz\SheetService;
use Illuminate\Http\Request;

class ApiController
{
    protected $sheet;
    protected $sheets;
    protected $quizzes;

    public function __construct(
        SheetService $sheet,
        SheetRepositoryContracts $sheets,
        QuizRepositoryContract $quizzes
    ) {
        $this->sheet = $sheet;
        $this->sheets = $sheets;
        $this->quizzes = $quizzes;
    }

    public function show($id)
    {
        $sheet = $this->sheets->find($id);

        if (null === $sheet) {
            return response()->failed('没有找到资源');
        }

        $sheets = $this->sheets->findAll(
            [['activity_id', '=', $sheet->activity_id], ['user_id', '=', $sheet->user_id]],
            ['option_id', 'fill_content']
        )->toArray();

        $optionIds = [];
        $contents = [];

        foreach ($sheets as $item) {
            $optionIds = array_merge($optionIds, $item['option_id']);
            if ($item['fill_content']) {
                foreach ($item['fill_content'] as $i => $c) {
                    if (isset($item['option_id'][$i])) {
                        $_optionId = $item['option_id'][$i];
                        $contents[$_optionId] = $c;
                    }
                }
            }
        }

        $quizzes = $this->quizzes->findAllWithOptions($sheet->activity_id, ['id', 'type', 'title']);
        $types = $this->quizzes->types();
        $answer = [];

        foreach ($quizzes as $of => $quiz) {
            $answer[$of]['title'] = sprintf('%s [%s]', $quiz->title, $types[$quiz->type]);

            $opts = is_null($quiz->options) ? [] : $quiz->options;

            foreach ($opts as $i => $opt) {
                if (in_array($opt->id, $optionIds, false)) {
                    $texts[] = $opt->text;
                    if (isset($contents[$opt->id])) {
                        $texts[] = $contents[$opt->id];
                    }
                }
            }

            $answer[$of]['answer'] = implode(' | ', $texts);
        }


        return response()->success($answer);
    }

    public function filter(Request $request)
    {
        // pass
    }
}
